/*
 * @Date: 2025-02-28 16:48:45
 * @LastEditTime: 2025-03-27 11:25:58
 * @FilePath: \LeagueBard\frontend\src\LcuApi\gameAsset.ts
 * @Description: 加载静态资源
 */
import {
  getChampionsApi,
  getChampionsPositionsApi,
  getGameQueuesApi,
  getImageByteApi,
  getItemsApi,
  getMapsApi,
  getProfileIconsApi,
  getRunesApi,
  getRuneStylesApi,
  getSummonerSpellsApi,
} from '@/api/client/basicDataApi'

class GameAssetManager {
  private cache: { [key: string]: any } = {};
  private loading: { [key: string]: Promise<any> } = {}; // 新增：用于记录正在加载的请求

  /**
   * 由于ssl证书问题，无法获取用户信息，所以需要使用代理
   * @returns {string} 图片的base64编码
   */
  public async getImageByte(url: string) {
    const base64 = await getImageByteApi(url);
    return base64;
  }

  // 获取头像列表
  public async getProfileIcons() {
    if (this.cache.profileIcons && this.cache.profileIcons.length > 0) {
      return this.cache.profileIcons;
    }
    if (this.loading.profileIcons) {
      return await this.loading.profileIcons; // 如果正在加载，等待加载完成
    }
    this.loading.profileIcons = getProfileIconsApi().then((data) => {
      this.cache.profileIcons = data;
      delete this.loading.profileIcons; // 加载完成后删除记录
      return data;
    });
    return await this.loading.profileIcons;
  }

  // 获取英雄列表
  public async getChampions() {
    if (this.cache.champions && this.cache.champions.length > 0) {
      return this.cache.champions;
    }
    if (this.loading.champions) {
      return await this.loading.champions;
    }
    this.loading.champions = getChampionsApi().then(async (data) => {
      const positions = await getChampionsPositionsApi()
      data.forEach((item) => {
        if (positions[item.id]) {
          item.positions = positions[item.id]?.recommendedPositions || []
        }
      })
      this.cache.champions = data;
      delete this.loading.champions;
      return data;
    });
    return await this.loading.champions;
  }

  // 获取召唤师技能列表
  public async getSummonerSpells() {
    if (this.cache.summonerSpells && this.cache.summonerSpells.length > 0) {
      return this.cache.summonerSpells;
    }
    if (this.loading.summonerSpells) {
      return await this.loading.summonerSpells;
    }
    this.loading.summonerSpells = getSummonerSpellsApi().then((data) => {
      this.cache.summonerSpells = data;
      delete this.loading.summonerSpells;
      return data;
    });
    return await this.loading.summonerSpells;
  }

  // 获取符文列表
  public async getRunes() {
    if (this.cache.runeList && this.cache.runeList.length > 0) {
      return this.cache.runeList;
    }
    if (this.loading.runeList) {
      return await this.loading.runeList;
    }
    this.loading.runeList = Promise.all([getRuneStylesApi(), getRunesApi()]).then(([runesStyles, runes]) => {
      const arr = [...runesStyles.styles, ...runes];
      this.cache.runeList = arr;
      delete this.loading.runeList;
      return arr;
    });
    return await this.loading.runeList;
  }

  // 获取装备列表
  public async getItems() {
    if (this.cache.items && this.cache.items.length > 0) {
      return this.cache.items;
    }
    if (this.loading.items) {
      return await this.loading.items;
    }
    this.loading.items = getItemsApi().then((data) => {
      this.cache.items = data;
      delete this.loading.items;
      return data;
    });
    return await this.loading.items;
  }

  // 获取模式列表
  public async getGameQueues() {
    if (this.cache.gameQueues && this.cache.gameQueues.length > 0) {
      return this.cache.gameQueues;
    }
    if (this.loading.gameQueues) {
      return await this.loading.gameQueues;
    }
    this.loading.gameQueues = getGameQueuesApi().then((data) => {
      this.cache.gameQueues = data;
      delete this.loading.gameQueues;
      return data;
    });
    return await this.loading.gameQueues;
  }

  // 获取地图列表
  public async getMaps() {
    if (this.cache.maps && this.cache.maps.length > 0) {
      return this.cache.maps;
    }
    if (this.loading.maps) {
      return await this.loading.maps;
    }
    this.loading.maps = getMapsApi().then((data) => {
      const arr = [];
      for (const key in data) {
        if (key && data[key].length > 0) {
          arr.push({
            id: key,
            name: data[key][0].name,
            iconPath: data[key][0].assets['game-select-icon-hover'],
          });
        }
      }
      this.cache.maps = arr;
      delete this.loading.maps;
      return arr;
    });
    return await this.loading.maps;
  }

  // 获取玩家头像
  public async getProfileIcon(iconId) {
    const ids = typeof iconId === 'number' ? [iconId] : iconId;
    const profileIcon = [];
    const profileIcons = await this.getProfileIcons();
    for (const id of ids) {
      const icon = profileIcons.find((icon) => icon.id === id);
      icon.url = await this.getImageByte(icon.iconPath);
      profileIcon.push(icon);
    }
    return typeof iconId === 'number' ? profileIcon[0] : profileIcon;
  }

  /**
   * 获取英雄信息（不包括头像）
   * @param {Array|string} championIds - 英雄的ID标识符
   * @returns {string} 英雄头像图标的URL字符串
   */
  public async getChampionInfo(championIds) {
    const ids = typeof championIds === 'number' ? [championIds] : championIds;
    const championInfo = [];
    const champions = await this.getChampions();
    for (const championId of ids) {
      const champion = champions.find((champion) => champion.id === championId);
      championInfo.push(champion);
    }
    return typeof championIds === 'number' ? championInfo[0] : championInfo;
  }

  /**
   * 获取英雄头像图标URL
   * @param {number|string} championId - 英雄的ID标识符
   * @returns {string} 英雄头像图标的URL字符串
   */
  public async getSquareById(championId) {
    const champions = await this.getChampions();
    const champion = champions.find((champion) => champion.id === championId);
    return await this.getImageByte(champion.squarePortraitPath);
  }

  /**
   * 获取召唤师技能信息
   * @param {Array|string} spellIds - 召唤师技能的ID标识符
   * @returns {string} 召唤师技能信息的URL字符串
   */
  public async getSummonerSpellInfo(spellIds) {
    const ids = typeof spellIds === 'number' ? [spellIds] : spellIds;
    const summonerSpellInfo = [];
    const summonerSpells = await this.getSummonerSpells();
    for (const spellId of ids) {
      const spell = summonerSpells.find((spell) => spell.id === spellId) || {};
      spell.url = await this.getImageByte(spell.iconPath);
      summonerSpellInfo.push(spell);
    }
    return typeof spellIds === 'number' ? summonerSpellInfo[0] : summonerSpellInfo;
  }

  /**
   * 获取符文信息
   * @param {Array|string} runeIds - 符文的ID标识符
   * @returns {string} 符文信息的URL字符串
   */
  public async getRuneInfo(runeIds) {
    const ids = typeof runeIds === 'number' ? [runeIds] : runeIds;
    const runeInfo = [];
    const runeList = await this.getRunes();
    for (const runeId of ids) {
      const rune = runeList.find((rune) => rune.id === runeId) || {};
      rune.url = await this.getImageByte(rune.iconPath);
      runeInfo.push(rune);
    }
    return typeof runeIds === 'number' ? runeInfo[0] : runeInfo;
  }

  /**
   * 获取装备信息
   * @param {Array|string} itemIds - 装备的ID标识符
   * @returns {string} 装备信息的URL字符串
   */
  public async getItemInfo(itemIds) {
    const ids = typeof itemIds === 'number' ? [itemIds] : itemIds;
    const itemInfo = [];
    const items = await this.getItems();
    for (const itemId of ids) {
      const item = items.find((item) => item.id === itemId) || {};
      item.url = await this.getImageByte(item.iconPath);
      itemInfo.push(item);
    }
    return typeof itemIds === 'number' ? itemInfo[0] : itemInfo;
  }

  // 获取模式信息
  public async getGameQueueInfo(queueIds) {
    const ids = typeof queueIds === 'number' ? [queueIds] : queueIds;
    const gameQueueInfo = [];
    const gameQueues = await this.getGameQueues();
    for (const queueId of ids) {
      const queue = gameQueues.find((queue) => queue.id === queueId) || {};
      gameQueueInfo.push(queue);
    }
    return typeof queueIds === 'number' ? gameQueueInfo[0] : gameQueueInfo;
  }

  // 获取地图信息
  public async getMapInfo(mapIds) {
    const ids = typeof mapIds === 'number' ? [mapIds] : mapIds;
    const Maps = [];
    const mapList = await this.getMaps();
    for (const mapId of ids) {
      const mapInfo = mapList.find((mapInfo) => mapInfo.id === String(mapId)) || {};
      mapInfo.url = await this.getImageByte(`/${mapInfo.iconPath}`);
      Maps.push(mapInfo);
    }
    return typeof mapIds === 'number' ? Maps[0] : Maps;
  }
}

// 创建单例实例
const gameAssetManager = new GameAssetManager();

export { gameAssetManager };
